---
import type { CollectionEntry } from 'astro:content'

import BaseLayout from './BaseLayout.astro'
import CollectionRelated from '../components/CollectionRelated.astro'
import PreviewWrapper from '../components/PreviewWrapper.astro'

type Props = CollectionEntry<'collection'>['data']

const { category, components, description, slug, terms, title, wrapper } = Astro.props

const formattedComponents = components
  .map((component, index) => {
    const { dark, ...rest } = component

    const baseComponent = {
      ...rest,
      dark: false,
      id: `component-${index + 1}`,
      index: index + 1,
    }

    if (!dark) {
      return [baseComponent]
    }

    const contributors =
      Object.prototype.toString.call(dark) === '[object Object]'
        ? // @ts-expect-error We know dark is an object at this point.
          dark.contributors
        : component.contributors

    return [
      baseComponent,
      {
        ...rest,
        contributors,
        dark: true,
        id: `component-${index + 1}-dark`,
        index: index + 1,
        title: `${component.title} (Dark)`,
      },
    ]
  })
  .flat()
---

<BaseLayout description={description} title={title}>
  <main class="mx-auto max-w-7xl space-y-8 px-4 py-8">
    <slot />

    <div class="space-y-8">
      {
        formattedComponents.map(({ contributors, dark, id, index, plugins, title }) => (
          <div id={id} class="space-y-4">
            <a
              href={`#${id}`}
              class="inline-block focus:ring-2 focus:ring-pink-500 focus:outline-0"
            >
              <h2 class="text-xl font-bold text-stone-900">{title}</h2>
            </a>

            <PreviewWrapper
              category={category}
              contributors={contributors}
              dark={dark}
              index={index}
              plugins={plugins}
              slug={slug}
              title={title}
              wrapper={wrapper}
            />
          </div>
        ))
      }
    </div>

    <CollectionRelated terms={terms} slug={slug} category={category} />
  </main>
</BaseLayout>
